<template>
  <div>
    <Row>
      <Card>
        <p slot="title">
          <Icon type="navicon-round"></Icon>
          身高记录详情
        </p>
        <VmBtable type="edit" ref="VmBtable"
                  :columns="dataColumns"
                  :data="dataTable"
                  :searchparam="searchParam"
                  :importBtn="false"
                  :batchDelBtn="false"
                  :downTemplate="false"
                  v-on:searchFn="searchFn"
                  v-on:page-change="pageChangeFn"
                  v-on:addFn="addFn"
                  v-on:editFn="editFn"
                  v-on:deleteFn="deleteFn"
                  :operate="operate"
                  placeholder="年级关键字"
                  searchText="年级查询："
                  cleanText="刷新"
                  v-on:exportFn="exportHeightDetailRecordFn"
                  v-on:restFn="restFn">
          <div slot="search" class="db_inline">
            班级查询：
            <Input v-model="searchParam.baseHeightRecordDetailClass" placeholder="班级关键字" style="width: 180px;"/>
          </div>
          <div slot="operation" class="db_inline" >
            <Button type="info" v-on:click="backToFn">
              <Icon type="arrow-left-c"></Icon>
              <span>返回</span>
            </Button>
          </div>
        </VmBtable>
      </Card>
    </Row>
    <Modal v-model="modal.visible" :title="modal.title" v-on:on-ok="subForm" :mask-closable="false" width="540"
           v-on:on-cancel="cancelSub">
      <Form ref="Form" :model="modal.form" :label-width="100" label-position="right" :rules="modal.rules">
<!--        <FormItem label="年级" prop="baseHeightRecordDetailGrade">-->
<!--          <Input v-model="modal.form.baseHeightRecordDetailGrade" placeholder="输入年级" style="width:83%"/>-->
<!--        </FormItem>-->
<!--        <FormItem label="班级" prop="baseHeightRecordDetailClass">-->
<!--          <Input v-model="modal.form.baseHeightRecordDetailClass"  placeholder="输入班级" style="width:83%"/>-->
<!--        </FormItem>-->
        <FormItem label="班级" prop="clazzId">
<!--          <Select v-model="modal.form.clazzId" label-in-value @on-change="clazzChange">-->
          <Select v-model="modal.form.clazzId" label-in-value @on-change="clazzChange" style="width:83%">
            <Option v-for="item in clazzList" :value="item.id" :key="item.id">{{item.gradeName}}-{{item.name }}
            </Option>
          </Select>
        </FormItem>
<!--        <FormItem label="姓名" prop="baseHeightRecordDetailName">-->
<!--          <Input v-model="modal.form.baseHeightRecordDetailName" placeholder="输入姓名" style="width:83%"/>-->
<!--        </FormItem>-->
        <FormItem label="姓名" prop="baseStudentId">
<!--          <Select v-model="modal.form.baseStudentId" :key="studentList.toString()">-->
          <Select v-model="modal.form.baseStudentId" :key="studentList.toString()" :clearable="false" @on-change="studentChange(modal.form.baseHeightRecordDetailName)" style="width:83%">
<!--            <Option v-for="item in studentList" :value="item.id" :key="item.id">{{item.clazzName}}-{{item.name }}</Option>-->
            <Option v-for="item in studentList" :value="item.id" :key="item.id">{{item.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="身高" prop="baseHeightRecordDetailHeight">
          <InputNumber :max="200" :min="50" :step="1" v-model="modal.form.baseHeightRecordDetailHeight"></InputNumber>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="modal.visible=false">取消</Button>
        <Button type="primary" @click="subForm" :loading="modal.loading">确定</Button>
      </div>
    </Modal>
    <Modal v-model="device.visible" :title="device.title" :mask-closable="false" width="70%">
      <div>名称搜索：
        <Input v-model="device.search.deviceName" icon="search" @on-change="queryTerminal" placeholder="设备名关键字"
               style="width: 180px;"/>
      </div>
      <div style="margin-top: 20px">
        <Table ref="terminal" :columns="device.equColumns"
               :data="device.equData"
               @on-selection-change="selectChange"
               height="500"/>
      </div>
      <Row type="flex" justify="end" class="footer">
        <div class="margin-top-10">
          <span>总共 {{device.search.total}} 条记录 &nbsp;</span>
          <Page class="db_inline" :total="device.search.total" :current="device.search.current"
                :page-size="device.search.size"
                @on-change="terminalPageChange" show-elevator></Page>
        </div>
      </Row>
      <div slot="footer">
        <Button type="text" @click="device.visible=false">取消</Button>
        <Button type="primary" @click="sureUpdateFn" :loading="modal.loading">升级选中</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import API from "@/api/api";
  import VmBtable from "@/components/vm/vm-btable";
  import Cookie from "js-cookie"
  import Axios from 'axios'

  export default {
    components: {
      VmBtable
    },
    data() {
      return {
        loginType: Cookie.getJSON('loginType'),
        searchParam: {
          current: 1,
          size: 20,
          total: 0,
          name: '',
          version: '',
          baseHeightRecordDetailGrade: '',
          baseHeightRecordDetailClass: '',
          baseHeightRecordId:'',
        },
        exportPath: Cookie.getJSON('cdnUrl'),
        action: Axios.defaults.baseURL + '/cos/upload',
        headers: {
          Authorization: "Bearer " + Cookie.getJSON('TOKEN'),
        },
        dataColumns: [
          {
            title: '序号',
            type: 'index',
            align: 'center',
            width: 100
          },
          {
            title: '姓名',
            align: 'center',
            key: 'baseHeightRecordDetailName',
          },
          {
            title: '年级',
            align: 'center',
            key: 'baseHeightRecordDetailGrade',
          },
          {
            title: '班级',
            align: 'center',
            key: 'baseHeightRecordDetailClass',
          },
          {
            title: '身高（cm）',
            align: 'center',
            key: 'baseHeightRecordDetailHeight',
          },
          // {
          //   title: '备注',
          //   align: 'center',
          //   key: 'status',
          //   render: (h, param) => {
          //     let status = param.row.status;
          //     if (status) {
          //       return h('div', {style: {color: 'green'}}, '上架')
          //     } else {
          //       return h('div', {style: {color: 'gray'}}, '下架')
          //     }
          //   }
          // },

          {
            title: '操作',
            align: 'center',
            minWidth: 140,
            render: (h, params) => {
              let btn = [];
              let detailBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.editFn(params.row)
                  }
                }
              }, '编辑');
              let delBtn = h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.deleteFn(params.row)
                  }
                }
              }, '删除');
              let updateBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.updateFn(params.row)
                  }
                }
              }, '升级设备');
              let upBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.changeStatus(params.row)
                  }
                }
              }, '上架');
              let downBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.changeStatus(params.row)
                  }
                }
              }, '下架');
              // let informationBtn = h('Button', {
              //   props: {
              //     type: 'info',
              //     size: 'small',
              //   },
              //   style: {
              //     marginRight: '5px'
              //   },
              //   on: {
              //     click: () => {
              //       this.changeStatus(params.row)
              //     }
              //   }
              // }, '详情');
              let status = params.row.status;
              if (status) {
                btn = [detailBtn, downBtn, updateBtn, delBtn]
              } else {
                btn = [detailBtn, upBtn, updateBtn, delBtn]
              }
              if (this.loginType !== 'platform') {
                // btn = [updateBtn]
                // btn = [detailBtn, informationBtn, delBtn]
                btn = [detailBtn, delBtn]
              }
              return h('div', btn);
            }
          }
        ],
        operate: [],
        dataTable: [],
        clazzList: [],
        studentList: [],
        modal: {
          visible: false,
          title: '',
          isEdit: false,
          loading: false,
          form: {
            baseHeightRecordDetailName: '',
            baseHeightRecordDetailGrade: '',
            baseHeightRecordDetailClass: 1,
            baseHeightRecordDetailHeight: 120,
            baseHeightRecordId: '',
            clazzId: '',
            clazzName: '',
            baseStudentId: '',
            studentName: '',
          },
          rules: {
            'clazzId': [{
              type:'number',
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'baseStudentId': [{
              type:'number',
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'baseHeightRecordDetailHeight': [{
              type:'number',
              required: true,
              trigger: 'blur',
              message: '必填项'
            }]
          }
        },
        device: {
          visible: false,
          title: '',
          equColumns: [
            {
              type: 'index',
              title: '序号',
              align: 'center',
              minWidth: 40
            },
            {
              title: '设备名',
              key: 'deviceName',
              minWidth: 160,
              align: 'center'
            },
            {
              title: 'mac地址',
              key: 'mac',
              minWidth: 160,
              align: 'center'
            },
            {
              title: '软件版本',
              key: 'softwareVersion',
              minWidth: 200,
              align: 'center',
            },
            {
              title: '创建时间',
              key: 'createTime',
              minWidth: 150,
              align: 'center',
            },
            {
              type: 'selection',
              title: '全选',
              align: 'center',
              minWidth: 20
            },
          ],
          equData: [],
          search: {
            current: 1,
            size: 20,
            deviceName: '',
            total: 0
          },
          form: {
            apkId: '',
            array: []
          }
        }
      };
    },
    methods: {
      changeStatus(data) {
      	this.$roter.push({
      		path:'/',
      		query:''
      	})
        this.$Modal.confirm({
          title: '提示',
          content: '是否下架/下架该APK？',
          onOk: () => {
            API.changeStatus(data).then(resp => {
              this.queryFn();
            })
          }, onCancel: () => {

          }
        });
      },
      addFn() {
        Object.assign(this.modal, {
          visible: true,
          isEdit: false,
          title: '添加',
          form: {baseHeightRecordDetailHeight: 120}
        })
      },
      editFn(data) {
        // clazzChange(data) {
        //   if (data) {
        //     this.modal.form.clazzId = data.value;
        //     this.modal.form.clazzName = data.label;
        //     this.fetchStudentByClazzId(data.value);
        //   }
        // },
        this.modal.form.clazzId = data.clazzId;
        // this.modal.form.clazzName = data.baseHeightRecordDetailName;
        this.modal.form.baseStudentId = data.baseStudentId;
        this.fetchStudentByClazzId(data.clazzId,data.baseStudentId);
        Object.assign(this.modal, {
          visible: true,
          isEdit: true,
          title: '编辑',
          form: data
        })
        // this.modal.form.uploadList = [{name: data.fileName, url: ''}];
      },
      deleteFn(data) {
        this.$Modal.confirm({
          title: '警告',
          content: '是否删除该身高记录详情？',
          onOk: () => {
            API.deleteHeightRecordDetail({id: data.baseHeightRecordDetailId}).then(resp => {
              this.queryFn();
            })
          },
          onCancel() {
          }
        })
      },
      updateFn(data) {
        this.device.visible = true;
        this.device.title = '升级设备APK（版本号：' + data.version + '）';
        this.device.form.apkId = data.id;
        this.queryTerminal();
      },
      queryTerminal() {
        API.fetchDevice(this.device.search).then(resp => {
          let records = resp.data.records;
          for (let i in records) {
            if (this.device.form.array.lastIndexOf(records[i].id) !== -1) {
              records[i]._checked = true;
            }
          }
          this.device.equData = records;
          this.device.search.total = resp.data.total;
          this.device.search.current = resp.data.current;
        })
      },
      selectChange(array) {
        this.device.form.array = array.map(d => d.id);
      },
      terminalPageChange(current) {
        this.device.search.current = current;
        this.queryTerminal();
      },
      sureUpdateFn() {
        this.$Modal.confirm({
          title: '提示',
          content: '升级需要时间比较长，请耐心等待，是否继续？',
          onOk: () => {
            API.updateDeviceApk(this.device.form).then(resp => {
              this.$Notice.success({
                title: '提示',
                desc: '命令下发成功,请等待设备自动升级',
              })
              this.device.visible = false;
            })
          },
          onCancel: () => {
          }
        })
      },
      beforeUpload() {
        let key = this.modal.form.key;
        if (key) {
          this.$Notice.warning({
            title: '提示',
            desc: '请先删除已上传的APK'
          })
          return false;
        }
        this.$Spin.show();
      },
      removeFile() {
        let key = this.modal.form.key;
        if (key) {
          API.deleteFromTencent({fileName: key}).then(resp => {
            this.modal.form.key = '';
            this.modal.form.fileName = '';
          });
        }
      },
      uploadSuccess(res, file, fileList) {
        this.modal.form.key = res.data.key;
        this.modal.form.fileName = res.data.fileName;
        this.$Spin.hide();
      },
      restFn() {
        this.searchParam.current = 1;
        this.searchParam.size = 20;
        this.searchParam.name = '';
        this.searchParam.version = '';
        this.searchParam.baseHeightRecordDetailGrade = '';
        this.searchParam.baseHeightRecordDetailClass = '';
        this.queryFn();
      },
      queryFn() {
        API.fetchHeightRecordDetailByHeightRecordId(this.searchParam.baseHeightRecordId).then(
          res => {
            let data = res.data;
            this.dataTable = data;
            this.searchParam.total = data.total;
          },
          error => {
            this.$Message.info(error.msg);
          }
        );

      },
      complete() {
        Object.assign(this.modal, {
          visible: false,
          title: '',
          loading: false,
        });
        this.$refs.Form.resetFields();
      },
      subForm() {
        this.$refs.Form.validate(valid => {
          if (valid) {
            let data = Object.assign(this.modal.form);
              data.baseHeightRecordId = this.$route.query.id;
              if (data.baseHeightRecordDetailId) {
                API.updateHeightRecordDetail(data).then(resp => {
                  this.queryFn();
                  this.complete();
                })
              } else {
                API.createHeightRecordDetail(data).then(resp => {
                  this.queryFn();
                  this.complete();
                })
              }
          }
        })
      },
      cancelSub() {

      },
      pageChangeFn(current) {
        this.searchParam.current = current;
        this.queryFn();
      },
      searchFn(value) {
        this.searchParam.baseHeightRecordDetailGrade = value;
        API.fetchHeightRecordDetail(this.searchParam).then(
          res => {
            let data = res.data;
            this.dataTable = data.records;
            this.searchParam.total = data.total;
          },
          error => {
            this.$Message.info(error.msg);
          }
        );
      },
      backToFn() {
        this.$router.push({
          path:'/height-record',
          query:{

          }
        })
      },
      fetchKindergartenClazz() {
        API.fetchKindergartenClazz().then(resp => {
          this.clazzList = resp.data;

        })
      },
      clazzChange(data) {
        if (data) {
          this.modal.form.clazzId = data.value;
          this.modal.form.clazzName = data.label;
          this.fetchStudentByClazzId(data.value,'');
        }
      },
      fetchStudentByClazzId(clazzId,baseStudentId) {
        API.fetchStudentByClazzId(clazzId).then(resp => {
          if(baseStudentId){
            this.modal.form.baseStudentId = baseStudentId
          }
          this.studentList = resp.data;
        })
      },
      studentChange(data) {
        // console.log(data);
      },
      exportHeightDetailRecordFn(value) {
        this.$Modal.confirm({
          title: '提示',
          content: '是否导出符合筛选条件的报告？',
          // content: '是否导出当前数据？',
          onOk: () => {
            this.searchParam.baseHeightRecordDetailGrade=value;
            API.exportHeightRecordDetail(this.searchParam);
          },
          onCancel: () => {

          }
        })
      },
    },
    created() {
      this.searchParam.baseHeightRecordId=this.$route.query.id;
    },
    mounted() {
      this.queryFn();
      this.fetchKindergartenClazz();
    }
  }
</script>

<style scoped>

</style>
